package com.spzx.order.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.spzx.cart.api.RemoteCartService;
import com.spzx.cart.api.domain.CartInfo;
import com.spzx.common.core.constant.SecurityConstants;
import com.spzx.common.core.context.SecurityContextHolder;
import com.spzx.common.core.domain.R;
import com.spzx.common.core.exception.ServiceException;
import com.spzx.common.core.utils.DateUtils;
import com.spzx.common.rabbit.constant.MqConst;
import com.spzx.common.rabbit.service.RabbitService;
import com.spzx.order.domain.OrderInfo;
import com.spzx.order.domain.OrderItem;
import com.spzx.order.domain.OrderLog;
import com.spzx.order.form.OrderForm;
import com.spzx.order.mapper.OrderInfoMapper;
import com.spzx.order.mapper.OrderItemMapper;
import com.spzx.order.mapper.OrderLogMapper;
import com.spzx.order.service.OrderInfoService;
import com.spzx.order.vo.TradeVo;
import com.spzx.product.api.RemoteProductService;
import com.spzx.product.api.RemoteSkuStockService;
import com.spzx.product.api.model.ProductSku;
import com.spzx.product.vo.SkuLockVo;
import com.spzx.product.vo.SkuPriceVo;
import com.spzx.user.api.RemoteUserAddressService;
import com.spzx.user.api.domain.UserAddress;
import io.jsonwebtoken.lang.Collections;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.data.redis.core.script.RedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * <p>
 * 订单 服务实现类
 * </p>
 *
 * @author atguigu
 * @since 2025-05-09
 */
@Service
public class OrderInfoServiceImpl extends ServiceImpl<OrderInfoMapper, OrderInfo> implements OrderInfoService {

    @Autowired
    private RemoteCartService cartService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private RemoteProductService remoteProductService;

    @Autowired
    private RemoteCartService remoteCartService;


    @Autowired
    private RemoteUserAddressService remoteUserAddressService;


    @Autowired
    private RemoteSkuStockService remoteSkuStockService;

    @Autowired
    private OrderItemMapper orderItemMapper;

    @Autowired
    private RabbitService rabbitService;

    /**
     * 订单结算页相关参数封装
     *
     * @return
     */
    @Override
    public TradeVo trade() {
        //0.创建订单结算VO对象
        TradeVo tradeVo = new TradeVo();

        //1.远程调用购物车服务，获取选中的商品列表，封装订单明细列表
        R<List<CartInfo>> r = cartService.getCartCheckedList(SecurityConstants.INNER);
        //1.1 验证远程调用是否成功
        if (R.FAIL == r.getCode()) {
            throw new ServiceException("远程调用购物车服务失败，原因：" + r.getMsg());
        }
        //1.2 获取到选中购物车商品列表
        List<CartInfo> cartInfoList = r.getData();
        //1.3 将购物车商品列表转为订单明细列表
        if (Collections.isEmpty(cartInfoList)) {
            throw new ServiceException("没有需要结算商品");
        }
        //1.4 将购物车商品转为订单明细
        List<OrderItem> orderItemList = cartInfoList
                .stream()
                .map(cartInfo -> {
                    OrderItem orderItem = new OrderItem();
                    BeanUtils.copyProperties(cartInfo, orderItem);
                    return orderItem;
                }).collect(Collectors.toList());
        tradeVo.setOrderItemList(orderItemList);

        //2.计算订单总金额
        BigDecimal totalAmount = new BigDecimal(0);
        for (OrderItem orderItem : orderItemList) {
            totalAmount = totalAmount.add(orderItem.getSkuPrice().multiply(new BigDecimal(orderItem.getSkuNum())));
        }
        tradeVo.setTotalAmount(totalAmount);


        //3.生成本次订单流水号-防止重复点击提交订单，存入Redis中 有效期5分钟
        String tradeNo = this.generateTradeNo();
        tradeVo.setTradeNo(tradeNo);

        //4.封装结算对象VO响应
        return tradeVo;
    }

    /**
     * 生成当前用户结算订单流水号
     *
     * @return
     */
    @Override
    public String generateTradeNo() {
        String tradeKey = "user:tradeNo:" + SecurityContextHolder.getUserId();
        String tradeNo = UUID.randomUUID().toString();
        redisTemplate.opsForValue().set(tradeKey, tradeNo, 5, TimeUnit.MINUTES);
        return tradeNo;
    }

    /**
     * 保存订单
     *
     * @param orderForm
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long submitOrder(OrderForm orderForm) {
        //1.业务校验,验证流水号,防止订单重复提交或长时间停留订单结算页
        String tradeKey = "user:tradeNo:" + SecurityContextHolder.getUserId();
        //1.1 通过Lua脚本验证流水号 KEYS[1]：流水号Key  ARGV[1]：用户提交流水号
        String script = "if redis.call(\"get\",KEYS[1]) == ARGV[1]\n" +
                "then\n" +
                "    return redis.call(\"del\",KEYS[1])\n" +
                "else\n" +
                "    return 0\n" +
                "end\n";
        RedisScript<Boolean> booleanRedisScript = new DefaultRedisScript<>(script, Boolean.class);
        Boolean flag = (Boolean) redisTemplate.execute(booleanRedisScript, Arrays.asList(tradeKey), orderForm.getTradeNo());
        if (!flag) {
            throw new ServiceException("流水号校验失败，请重新提交");
        }

        //2.验证订单中明细商品价格是否变更
        //2.1 根据订单明细列表中skuID列表，远程调用"商品服务"得到实时商品价格列表
        List<Long> skuIdList = orderForm.getOrderItemList().stream()
                .map(OrderItem::getSkuId)
                .collect(Collectors.toList());

        R<List<SkuPriceVo>> r = remoteProductService.getSkuPriceList(skuIdList, SecurityConstants.INNER);
        if (R.FAIL == r.getCode()) {
            throw new ServiceException("远程调用商品服务失败，原因：" + r.getMsg());
        }
        List<SkuPriceVo> skuPriceVoList = r.getData();
        Map<Long, BigDecimal> skuPriceMap =
                skuPriceVoList.stream().collect(Collectors.toMap(SkuPriceVo::getSkuId, SkuPriceVo::getSalePrice));

        //2.2 判断商品价格是否有变更，如果有变更
        String priceErrorMsg = "";
        for (OrderItem orderItem : orderForm.getOrderItemList()) {
            if (orderItem.getSkuPrice().compareTo(skuPriceMap.get(orderItem.getSkuId())) != 0) {
                priceErrorMsg += orderItem.getSkuName() + "\n";
            }
        }
        if (StringUtils.isNotBlank(priceErrorMsg)) {
            //2.2.1 如果是通过购物车车途径提交订单，则远程调用"购物车服务"更新购物车中商品价格
            if (!orderForm.getIsBuy()) {
                remoteCartService.updateCartPrice(SecurityConstants.INNER);
            }

            //2.2.2 则提示价格有变更，重新结算，引导用户购物车页面
            throw new ServiceException(priceErrorMsg + "以上商品价格有变动");
        }

        //4.如果商品价格未变更：保存订单及明细，日志
        OrderInfo orderInfo = this.saveOrder(orderForm);

        //5.TODO 尝试检查锁定商品库存，远程调用商品服务库存锁定
        List<OrderItem> orderItemList = orderForm.getOrderItemList();
        List<SkuLockVo> skuLockVoList = orderItemList.stream().map(orderItem -> {
            SkuLockVo skuLockVo = new SkuLockVo();
            BeanUtils.copyProperties(orderItem, skuLockVo);
            return skuLockVo;
        }).collect(Collectors.toList());
        R<String> r1 = remoteSkuStockService.checkAndLock(orderInfo.getOrderNo(), skuLockVoList, SecurityConstants.INNER);
        if (R.FAIL == r1.getCode()) {
            throw new ServiceException("库存锁定失败，原因：" + r1.getMsg());
        }
        String stockErrorMsg = r1.getData();
        if (StringUtils.isNotBlank(stockErrorMsg)) {
            throw new ServiceException(stockErrorMsg);
        }

        //6.保存订单成功后， 如果是通过购物车车途径提交订单，清理用户购物车
        if (!orderForm.getIsBuy()) {
            remoteCartService.deleteCartCheckedList(SecurityConstants.INNER);
        }
        //7.响应订单ID，对接支付页面
        //TODO :RabbitMQ(死信、延迟插件)发送延迟消息 作用：自动将超时未支付订单关闭（延迟关单）
        return orderInfo.getId();
    }


    /**
     * 保存订单相关信息
     *
     * @param orderForm
     * @return
     */
    @Override
    public OrderInfo saveOrder(OrderForm orderForm) {
        //1.保存订单信息
        Long userId = SecurityContextHolder.getUserId();
        String userName = SecurityContextHolder.getUserName();
        OrderInfo orderInfo = new OrderInfo();
        //1.1 用户信息
        orderInfo.setUserId(userId);
        orderInfo.setNickName(userName);
        //1.2 生成订单编号 形式：日期+全局唯一ID（雪花算法）
        String orderNo = DateUtils.dateTime() + IdWorker.getIdStr();
        orderInfo.setOrderNo(orderNo);
        //1.3 遍历订单明细列表计算订单总金额
        BigDecimal totalAmount = orderForm.getOrderItemList().stream()
                .map(OrderItem::getSkuPrice)
                //从0开始累加结合中每个元素值
                .reduce(BigDecimal.ZERO, BigDecimal::add);
        orderInfo.setTotalAmount(totalAmount);
        orderInfo.setOriginalTotalAmount(totalAmount);
        //1.4 订单状态：待付款
        orderInfo.setOrderStatus(0);
        orderInfo.setCreateBy(userName);
        orderInfo.setRemark(orderForm.getRemark());
        //1.5 封装订单收件人信息 远程调用"用户服务"得到收件人信息
        R<UserAddress> r = remoteUserAddressService.getUserAddress(orderForm.getUserAddressId(), SecurityConstants.INNER);
        if (R.FAIL == r.getCode()) {
            throw new ServiceException("远程调用用户服务失败，原因：" + r.getMsg());
        }
        UserAddress userAddress = r.getData();
        orderInfo.setReceiverName(userAddress.getName());
        orderInfo.setReceiverPhone(userAddress.getPhone());
        orderInfo.setReceiverTagName(userAddress.getTagName());
        orderInfo.setReceiverProvince(userAddress.getProvinceCode());
        orderInfo.setReceiverCity(userAddress.getCityCode());
        orderInfo.setReceiverDistrict(userAddress.getDistrictCode());
        orderInfo.setReceiverAddress(userAddress.getAddress());
        save(orderInfo);
        Long orderId = orderInfo.getId();

        //2.保存订单明细信息
        List<OrderItem> orderItemList = orderForm.getOrderItemList();
        if (!CollectionUtils.isEmpty(orderItemList)) {
            for (OrderItem orderItem : orderItemList) {
                orderItem.setOrderId(orderId);
                orderItem.setCreateBy(userName);
                orderItemMapper.insert(orderItem);
            }
        }
        //3.保存订单操作日志
        OrderLog orderLog = new OrderLog();
        orderLog.setOrderId(orderId);
        orderLog.setOperateUser(userId.toString());
        orderLog.setProcessStatus(0);
        orderLog.setNote(orderForm.getRemark());
        orderLog.setCreateBy(userName);
        orderLogMapper.insert(orderLog);
        return orderInfo;
    }

    /**
     * 订单结算页面渲染
     *
     * @param skuId
     * @return
     */
    @Override
    public TradeVo buy(Long skuId) {
        //1.创建订单确认VO对象
        TradeVo tradeVo = new TradeVo();
        //2.封装订单明细
        //2.1 远程调用"商品服务"查询商品信息
        R<ProductSku> r = remoteProductService.getProductSku(skuId, SecurityConstants.INNER);
        if (R.FAIL == r.getCode()) {
            throw new ServiceException("远程调用商品服务失败，原因：" + r.getMsg());
        }
        ProductSku productSku = r.getData();
        //2.2 封装订单明细列表
        OrderItem orderItem = new OrderItem();
        orderItem.setSkuId(skuId);
        orderItem.setSkuName(productSku.getSkuName());
        orderItem.setThumbImg(productSku.getThumbImg());
        orderItem.setSkuPrice(productSku.getSalePrice());
        orderItem.setSkuNum(1);
        List<OrderItem> orderItemList = Arrays.asList(orderItem);
        tradeVo.setOrderItemList(orderItemList);
        //3.封装订单总金额
        tradeVo.setTotalAmount(orderItem.getSkuPrice());
        //4.生成流水号
        String tradeNo = this.generateTradeNo();
        tradeVo.setTradeNo(tradeNo);
        //5.设置立即购买为：true
        tradeVo.setIsBuy(true);
        return tradeVo;
    }

    /**
     * 查询指定用户订单列表
     *
     * @param userId
     * @param orderStatus
     * @return
     */
    @Override
    public List<OrderInfo> userOrderInfoList(Long userId, String orderStatus) {
        //1.查询订单列表
        LambdaQueryWrapper<OrderInfo> queryWrapper = new LambdaQueryWrapper<OrderInfo>()
                .eq(OrderInfo::getUserId, userId)
                .eq(!StringUtils.isEmpty(orderStatus), OrderInfo::getOrderStatus, orderStatus);
        List<OrderInfo> orderInfoList = list(queryWrapper);

        //2.查询订单明细列表,将订单明细列表封装到订单信息中
        if (!CollectionUtils.isEmpty(orderInfoList)) {
            List<Long> orderIdList = orderInfoList.stream().map(OrderInfo::getId).collect(Collectors.toList());
            LambdaQueryWrapper<OrderItem> orderItemLambdaQueryWrapper = new LambdaQueryWrapper<OrderItem>().in(OrderItem::getOrderId, orderIdList);
            List<OrderItem> orderItemList = orderItemMapper.selectList(orderItemLambdaQueryWrapper);

            //3.为订单封装订单明细列表 采用Stream流分组
            Map<Long, List<OrderItem>> orderItemListMap = orderItemList
                    .stream()
                    .collect(Collectors.groupingBy(OrderItem::getOrderId));

            for (OrderInfo orderInfo : orderInfoList) {
                orderInfo.setOrderItemList(orderItemListMap.get(orderInfo.getId()));
            }
        }
        return orderInfoList;
    }

    /**
     * 订单取消
     *
     * @param orderId
     */
    @Override
    public void cancelOrder(Long orderId) {
        //1.根据订单ID查询订单信息
        OrderInfo orderInfo = getById(orderId);

        //2.判断订单状态 如果是未支付才可以取消
        if (orderInfo != null && orderInfo.getOrderStatus() == 0) {
            orderInfo.setOrderStatus(-1);
            updateById(orderInfo);

            //3.TODO 基于RabbitMQ解除锁定库存
            rabbitService.sendMessage(
                    MqConst.EXCHANGE_PRODUCT,
                    MqConst.ROUTING_UNLOCK,
                    orderInfo.getOrderNo()
            );
        }
    }

    /**
     * 根据订单编号查询订单信息
     *
     * @param orderNo
     * @return
     */
    @Override
    public OrderInfo getByOrderNo(String orderNo) {
        //1.查询订单信息
        OrderInfo orderInfo = this.getOne(
                new LambdaQueryWrapper<OrderInfo>().eq(OrderInfo::getOrderNo, orderNo)
        );
        //2.查询订单明细列表
        if (orderInfo != null) {
            LambdaQueryWrapper<OrderItem> orderItemLambdaQueryWrapper
                    = new LambdaQueryWrapper<OrderItem>().eq(OrderItem::getOrderId, orderInfo.getId());
            List<OrderItem> orderItemList = orderItemMapper.selectList(orderItemLambdaQueryWrapper);
            orderInfo.setOrderItemList(orderItemList);
        }
        return orderInfo;
    }

    /**
     * 订单支付成功消息，修改订单状态
     *
     * @param orderNo
     */
    @Override
    public void paymentSuccess(String orderNo) {
        OrderInfo orderInfo = this.getByOrderNo(orderNo);
        if (orderInfo.getOrderStatus().intValue()==0) {
            orderInfo.setOrderStatus(1);
            this.updateById(orderInfo);
        }
    }

    @Autowired
    private OrderLogMapper orderLogMapper;

    /*public static void main(String[] args) {
        BigDecimal bigDecimal1 = new BigDecimal("0.01");
        BigDecimal bigDecimal2 = BigDecimal.valueOf(0.01);
        BigDecimal bigDecimal3 = new BigDecimal("0.010");
        System.out.println(bigDecimal2);


        //注意事项一：避免精度丢失 采用构造参数类型是字符串或者采用BigDecimal.valueOf初始化数值

        //比较两个数值 不能用equals比较
        System.out.println(bigDecimal1.equals(bigDecimal3));

        //注意事项二，比较值采用compareTo方法
        System.out.println(bigDecimal1.compareTo(bigDecimal3));


        //注意事项三，相除，设置保留精度，设置舍入模式
        BigDecimal bigDecimalA = new BigDecimal("1");
        BigDecimal bigDecimalB = new BigDecimal("3");
        System.out.println(bigDecimalA.divide(bigDecimalB, 2, RoundingMode.HALF_UP));

        BigDecimal bigDecimalC = new BigDecimal("0.2");
        BigDecimal bigDecimalD = new BigDecimal("0.03");
        System.out.println(bigDecimalC.multiply(bigDecimalD));


        //System.out.println(IdWorker.getId());
        //System.out.println(IdWorker.getId());
        //System.out.println(IdWorker.getId());
        //System.out.println(IdWorker.getId());
        //System.out.println(IdWorker.getId());
    }*/
}
